package com.ahdms.es.config;

import org.bouncycastle.asn1.x509.Certificate;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

/**
 * @author qinxiang
 * @date 2021-04-09 9:20
 */
public class PropertiesConfig {
    private static boolean hasInit = false;
    private static String pkmPath = "";
    private static String pkiRootCertPath = "";
    private static boolean ocspEnable = false;
    private static String ocspUrl = "";
    private static boolean crlEnable = false;
    private static boolean pkmCertVerify = false;
    private static Certificate pkmCert;
    private static Certificate pkiRootCert;

    public static void loadConfig(Properties properties) throws IOException {

        if(properties.containsKey("pkmPath")) {
            PropertiesConfig.pkmPath = properties.getProperty("pkmPath");
            setPkmCert();
        }
        if(properties.containsKey("pkmCertVerify")) {
            PropertiesConfig.pkmCertVerify = Boolean.valueOf(properties.getProperty("pkmCertVerify"));
        }
        if(properties.containsKey("pkiRootCertPath")) {
            PropertiesConfig.pkiRootCertPath = properties.getProperty("pkiRootCertPath");
            setPkiRootCert();
        }
        if(properties.containsKey("ocspEnable")) {
            PropertiesConfig.ocspEnable = Boolean.valueOf(properties.getProperty("ocspEnable"));
        }
        if(properties.containsKey("ocspUrl")) {
            PropertiesConfig.ocspUrl = properties.getProperty("ocspUrl");
        }
        if(properties.containsKey("crlEnable")) {
            PropertiesConfig.crlEnable = Boolean.valueOf(properties.getProperty("crlEnable"));
        }

        PropertiesConfig.hasInit = true;

    }

    private static void setPkmCert() throws IOException {
        byte[] bytes = Files.readAllBytes(Paths.get(PropertiesConfig.pkmPath));
        PropertiesConfig.pkmCert = Certificate.getInstance(bytes);
    }

    private static void setPkiRootCert() throws IOException {
        byte[] bytes = Files.readAllBytes(Paths.get(PropertiesConfig.pkiRootCertPath));
        PropertiesConfig.pkiRootCert = Certificate.getInstance(bytes);
    }

    public static Certificate getPkiRootCert(){
        return pkiRootCert;
    }

    public static Certificate getPkmCert(){
        return pkmCert;
    }

    public static String getPkmPath() {
        return pkmPath;
    }

    public static String getPkiRootCertPath() {
        return pkiRootCertPath;
    }

    public static boolean isOcspEnable() {
        return ocspEnable;
    }

    public static String getOcspUrl() {
        return ocspUrl;
    }

    public static boolean isCrlEnable() {
        return crlEnable;
    }

    public static boolean isHasInit(){
        return PropertiesConfig.hasInit;
    }

    public static boolean isPkmCertVerify() {
        return pkmCertVerify;
    }
}
